var ccv = {};

ccv.CK_CFG = "CCV_CK_CFG";

ccv.msgInterval = 0;

ccv.progress = {
    TimesBatchCnt: 30,
    T_SNAP: '',
    interval: 0,
    retLength: 0,
    times: 0
};

ccv.domJQ = {
    CFG_SELECT: null,
    MODULES: null,
    CFG_MODULES: null,
    
    MAIN: null,
    
    RADIO_MODE: null,
    RADIO_DIFF_AGAINST: null,
    
    USER_ACTIONS: null,
    REVS: null,
    DATES: null,
    WIDS: null,
    
    REV1: null,
    REV2: null,
    DATE1: null,
    DATE2: null,
    
    BTN_GENERATE: null,
    A_DELETE: null,
    A_OPTIONS: null,
    
    ALL_ANCHOR: null,
    
    MODULE_ANCHORS: null,
    
    HEADER: null,
    BTN_BROWSE: null,
    XML_NAME: null,
    UP_PASSWD: null,
    BTN_UPLOAD: null,
    OPTIONS: null,
    
    DLGS: null,
    DLG_PROGRESS: null,
    PROGRESS: null,
    DLG_DELETE: null,
    
    HISTORY: null
};



/**
 * ===========================================================================================
 * ccv dialog
 * 
 */
ccv.dlgs = {
    init: function() {
    	//jQuery.ui.dialog.defaults.bgiframe = true;
    	ccv.domJQ.DLG_DELETE.dialog({
    		width: 550,
    		height: 145,
    		closeOnEscape: true,
    		autoOpen: false,
    		modal: true,
    		title: "Delete config file confirmation",
    		buttons: {
    			"Delete": function() {
                    ccv.fn.wapi(
                        {
                            cmd: "DEL_XML_FILE", 
                            cfg: ccv.domJQ.CFG_SELECT.val(), 
                            cfgPwd: jQuery("div.dlgDelete input.deletePWD").val()
                        }, 
                        ccv.cb.successDelete, 
                        ccv.cb.errorDelete
                    );
    			},
    			
    			"Cancel": function() {
    				jQuery(this).dialog("close");
    			}	
    		}
    	});
    						
    	ccv.domJQ.DLG_PROGRESS.dialog({
    		width: 648,
    		closeOnEscape: false,
    		autoOpen: false,
    		modal: true,
    		title: 'Pls waiting for a moment, Report Generating ...',
    		close: function(event, ui) {
    			ccv.fn.resetProgress();							
    		},
    		buttons: {
    			'Close': function() {
    				ccv.fn.resetProgress();

    				jQuery(this).dialog('close');
    			}	
    		}
    	});        
    }    
};

ccv.ac = {
	formatItem: function(row) {
		return row[0] + "<div class='times'>Recent run times: " + row[1] + "</div>";	
	},
	
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='hlKey'>$1</span>");
	},
	
	init: function() {
		var iacRevsUrl = "/ccv-cgi/increment.search.pl";
		var iacWidsUrl = "/ccv-cgi/wids.increment.search.pl";
		var w1 = 215; 
		var w2 = 190;
		var h1 = 220;
		var h2 = 150;
		ccv.domJQ.REVS.autocomplete(iacRevsUrl, {
			width: w1,
			highlight: false,
			scroll: true,
			scrollHeight: h1,
			formatItem: ccv.ac.formatItem,
			highlight: ccv.ac.highlight
		});
		
		ccv.domJQ.WIDS.autocomplete(iacWidsUrl, {
			width: w1,
			highlight: false,
			scroll: true,
			scrollHeight: h1,
			highlight: ccv.ac.highlight
		});	
	
		ccv.domJQ.REV1.autocomplete(iacRevsUrl, {
			width: w2,
			highlight: false,
			scroll: true,
			scrollHeight: h2,
			formatItem: ccv.ac.formatItem,
			highlight: ccv.ac.highlight
		});
		
		ccv.domJQ.REV2.autocomplete(iacRevsUrl, {
			width: w2,
			highlight: false,
			scroll: true,
			scrollHeight: h2,
			formatItem: ccv.ac.formatItem,
			highlight: ccv.ac.highlight
		});		
	}
};



/**
 * ===========================================================================================
 * ccv ajax upload functions
 * 
 */
ccv.ajaxupload = {
    opts: {
        action: "/ccv-cgi/wapi.pl",
		id: 'ccvFileDom',
        name: 'uploadedFile',
        data: {
            cmd: "UP_XML_FILE"
        },
        autoSubmit: false,
        responseType: "json",
		
		onChange: function(file, ext) {
		    ccv.domJQ.BTN_UPLOAD.attr("disabled", false);
		    ccv.domJQ.XML_NAME.html(file);
		},
		
        onSubmit: function(file, ext){
            if (!(ext && /^(xml)$/.test(ext))){
				ccv.uifn.showMsg("Only *.xml can be uploaded!");
				ccv.domJQ.BTN_UPLOAD.attr("disabled", true);
				
                return false;
            }
        },
        
        onComplete: function(file, ret){
            if (ret.error == 0) {
                if (ret.id == "NEW") {
                    var opt = document.createElement('option');
                    opt.text = file;                
                    ccv.domJQ.CFG_SELECT[0].add(opt, null);
                 }
            }            
            ccv.uifn.showMsg(ret.desc);
            
            ccv.domJQ.BTN_UPLOAD.attr("disabled", false);
            ccv.domJQ.XML_NAME.html("");
        }
    },
    
    executor: null
    
};



/**
 * ===========================================================================================
 * ccv business functions
 * 
 */
ccv.fn = {
    wapi: function(jsonData, cbSuccess, cbError) {
        jQuery.ajax({
            url: "/ccv-cgi/wapi.pl",
            type: "GET",
            dataType: "json",
            data: jsonData,
            success: cbSuccess,
            error: cbError
        });
    },
    
    isDatesFormatValid: function(dates) {
        if (dates == "") {
            return true;
        }
                
        return /^(([<>]=?)?)(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})$/.test(dates)
            || /^(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})([<>]=?)(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})$/.test(dates);
    },    

    checkDatesLogic: function(dates) {
        var matched = dates.match(/^(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})([<>]=?)(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})$/);
        
        if (matched != null) {
            date1   = dates.match(/^(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})/g);
            date2   = dates.match(/(\d{1,2}[\-\/]\d{1,2}[\-\/]\d{4}|\d{4}[\-\/]\d{1,2}[\-\/]\d{1,2})$/g);
            arr1    = date1[0].split("/");
            arr2    = date2[0].split("/");
            arr11   = date1[0].split("-");
            arr21   = date2[0].split("-");
            
            arr1    = arr1.length > arr11.length ? arr1 : arr11;
            arr2    = arr2.length > arr21.length ? arr2 : arr21;
            
            var d1, d2;
            if (arr1[2] > 1000) {
                d1  = new Date(arr1[2], arr1[0] - 1, arr1[1]);
                d2  = new Date(arr2[2], arr2[0] - 1, arr2[1]);
            } else {
                d1  = new Date(arr1[0], arr1[1] - 1, arr1[2]);
                d2  = new Date(arr2[0], arr2[1] - 1, arr2[2]);            
            }
                            
            operator = dates.match(/([<>]=?)/g);
            
            strCompareExpression = "" + d1.getTime() + operator[0] + d2.getTime() + "";
            
            compareResult = eval(strCompareExpression);
    
            return compareResult;
        } 
        
        return true;
    },
    
    submitGenerate: function() {
        var ret = ccv.fn.beforeSubmitGenerate();
        
        if (!ret) {
            return false;
        }
        
        var pms = ccv.fn.constructPMs();
        
        if (!jQuery.isPlainObject(pms)) {
        	ccv.uifn.showMsg(pms);
        	return false;
        }
        ccv.fn.runGenerate(pms);
    },
    
    beforeSubmitGenerate: function() {
        jQuery.each(ccv.domJQ.USER_ACTIONS.find("input:text"), function(index, item) {
            item.value = jQuery.trim(item.value);
        });
        
        if (!ccv.domJQ.MODULES.find(":checked").length) {
            ccv.uifn.showMsg("Please select one or more modules");
            
            return false;
        }
        
        var reportMode = ccv.domJQ.USER_ACTIONS.find("input.radioMode:checked").val();
        var dates = ccv.domJQ.DATES.val();
        if (reportMode == "log") {
	        if (ccv.domJQ.REVS.val() == "" || ccv.domJQ.REVS.val() == "Input branch name here") {
	            ccv.uifn.showMsg("Revison(s)/Branch needed!");
	            ccv.domJQ.REVS.focus();
	            
	            return false;
	        }
                	
            if (ccv.fn.isDatesFormatValid(dates)) {
                if (!ccv.fn.checkDatesLogic(dates)) {
                    ccv.uifn.showMsg("Date scope logic is not valid, please correct it.");
                    ccv.domJQ.DATES.focus();
                    
                    return false;
                }                
            } else {
                ccv.uifn.showMsg("Dates format is not right, please refer to examples!");
                ccv.domJQ.DATES.focus();
                
                return false;                
            }
        } else {
        	var dfAgainst = ccv.domJQ.RADIO_DIFF_AGAINST.filter(":checked").val();
        	if (dfAgainst == "revisions") {
        		if (ccv.domJQ.REV1.val() == "" && ccv.domJQ.REV2.val() == "") {
	                ccv.uifn.showMsg("Revsions(rev1/rev2) needed!");
	                ccv.domJQ.REV1.focus();
	                
	                return false;                			
        		}
        	} else {
        		if (ccv.domJQ.DATE1.val() == "" && ccv.domJQ.DATE2.val() == "") {
	                ccv.uifn.showMsg("Dates(d1/d2) needed!");
	                ccv.domJQ.DATE1.focus();        			
	                
	                return false;        
        		}        		
        	}
        }        
        
        
        return true;
    },
    
    getOptions: function(pms) {
    	//options for cvs module
        var jqOstatBin = ccv.domJQ.OPTIONS.find("input.OstatBin");
        var jqOnotStatDeleted = ccv.domJQ.OPTIONS.find("input.OnotStatDeleted");
        var jqOcalcAllRevs = ccv.domJQ.OPTIONS.find("input.OcalcAllRevs");
        var jqOgenGraph = ccv.domJQ.OPTIONS.find("input.OgenGraph");
        var jqOstatBinLines = ccv.domJQ.OPTIONS.find("input.OstatBinLines");
        
        //options for svn module
        var jqOSvnWithLoc = ccv.domJQ.OPTIONS.find("input.OSvnWithLoc");
        
        var bitOgenGraph = 0;
        var bitOcalcAllRevs = 1;
        var bitOstatBin = 2;
        var bitOstatBinLines = 3;
        var bitOnotStatDeleted = 4;
    	
    	var bitOSvnWithLoc = 10;
    	var options  = 0;
   	
    	if (pms.mode == 0) {
        	if (jqOgenGraph[0].checked) {
        		options += Math.pow(2, bitOgenGraph);
        	}    	    
    		if (!pms.revs || pms.revs.toUpperCase() == 'HEAD' || pms.revs.toUpperCase() == 'MAIN') {
    			if (jqOcalcAllRevs[0].checked) {
    				options += Math.pow(2, bitOcalcAllRevs);
    			}
    		}
    		if (jqOstatBin[0].checked) {
    			options += Math.pow(2, bitOstatBin);
    		}
    		if (jqOstatBinLines[0].checked) {
    			options += Math.pow(2, bitOstatBinLines);
    		}	
    		if (jqOnotStatDeleted[0].checked) {
    			options += Math.pow(2, bitOnotStatDeleted);
    		}
    		//if (jqOSvnWithLoc[0].checked) {
    		if (1) {
    			options += Math.pow(2, bitOSvnWithLoc);
    		}	    			    									
    	}
    	
    	return options;	        
        
    },
    
    getFilterInfo: function() {
    	var jqFileInclude = ccv.domJQ.OPTIONS.find("input.fileInclude");
    	var jqFileExclude = ccv.domJQ.OPTIONS.find("input.fileExclude");
    	var jqDirInclude = ccv.domJQ.OPTIONS.find("input.dirInclude");
    	var jqDirExclude = ccv.domJQ.OPTIONS.find("input.dirExclude");
    	
    	var info = {
			fin: jqFileInclude.val(),
			fex: jqFileExclude.val(),	
			din: jqDirInclude.val(),
			dex: jqDirExclude.val()
    	};
		
		if (info.fin || info.fex || info.din || info.dex) {
	    	var sp = "__SP__";
	    	return info.fin + sp + info.fex + sp + info.din + sp + info.dex;
		} else {
			return "";	
		}
    },
    
    constructPMs: function() {
        var cfg = ccv.domJQ.CFG_SELECT.val();
        var revs 	= ccv.domJQ.REVS.val();
        var dates 	= ccv.domJQ.DATES.val();
        var wids 	= ccv.domJQ.WIDS.val();
        var rev1 	= ccv.domJQ.REV1.val();
        var rev2 	= ccv.domJQ.REV2.val();
        var date1 	= ccv.domJQ.DATE1.val();
        var date2 	= ccv.domJQ.DATE2.val();
    	
        if (ccv.domJQ.DIFF.find("input.diffAgainst:checked").val() == "revisions") {
        	date1 = "";	
        	date2 = "";
        } else {
        	rev1 = "";
        	rev2 = "";
        }	
    
        
        var pms = {};
        pms.cmd = "GENERATE";
        pms.mode = ccv.domJQ.USER_ACTIONS.find("input.radioMode:checked").val() == "log" ? 0 : 1;
        
        var opts = ccv.fn.getOptions(pms);
        var checkedModules = '';
        jQuery.each(ccv.domJQ.MODULES.find("input.chkAnchor[checked='true'][value!='']"), function(index, item) {
			checkedModules += item.value + ",";        		
        });
         
    	checkedModules = checkedModules.replace(/,$/, '');
    	    
        pms.cfg 	= cfg;
        pms.mids 	= checkedModules;
    	pms.opts	= opts;
        
    	if (pms.mode == 0) {
    		pms.rev = (!revs || revs.toUpperCase() == 'HEAD') ? 'MAIN' : revs;
    		pms.date = dates;
    		pms.wids = wids;
    	} else {
    		pms.r1 = rev1;
    		pms.r2 = rev2;
    		pms.d1 = date1;
    		pms.d2 = date2;
    		
    		var info = ccv.fn._getBranchRevsDatesBased();
    		var validRet = ccv.fn._checkSvnDfPmsValid(pms, info);
    		
    		if (validRet == 0) {
    			jQuery.extend(pms, info);
    		} else {
    			return validRet;	
    		}	
    	}
    	
		pms.filter = ccv.fn.getFilterInfo();
    	
    	return pms;
    },
    
    _checkSvnDfPmsValid: function(pms, info) {
    	if (info.rd1b == "trunk" && info.rd2b == "trunk") {
    		return "Can not diff between trunk and trunk!";
    	}
    	
		if (info.rd1b == "OnBranch" && !info.bb) {
			return "If r1/r2 are on branch, branch name must be provided!";
		}
    		    	
    	if (info.dfAgainst == "revs") {
    		if (info.rd1b == "OnBranch" || info.rd1b == "OnTrunk") {
    			if (!pms.r1 || !pms.r2 || isNaN(pms.r1) || isNaN(pms.r2)) {
    				return "r1/r2 must be a revison number when they are on branch/trunk!";
    			}
    		}
    	}
    	
    	return 0;
    },
    
    _getBranchRevsDatesBased: function() {
    	var info = {
    		dfAgainst: "",
    		rd1b: "", //rev1/date1 base on
    		rd2b: "", //rev2/date2 base on
    		bb: ""//branch name which revs/dates based on 
    	};
    	
    	if (ccv.domJQ.RADIO_DIFF_AGAINST.filter(':checked').val() == "revisions") {
    		info.dfAgainst = "revs";
    		info.rd1b = ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base").val();  
    		info.rd2b = ccv.domJQ.SVN_REV_BASE.filter(".svnRev2Base").val();
    		
    		if (info.rd1b == "OnBranch") {
    			info.bb = ccv.domJQ.DIFF.find("input.branchRevsBasedOn").val();
    		}
    	} else {
    		info.dfAgainst = "dates";
    		info.rd1b = ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base").val();  
    		info.rd2b = ccv.domJQ.SVN_REV_BASE.filter(".svnDate2Base").val();    		
    		
    		if (info.rd1b == "OnBranch") {
    			info.bb = ccv.domJQ.DIFF.find("input.branchDatesBasedOn").val();
    		}    		
    	}
    	
    	return info;
    },
    
    listenProgress: function() {
    	ccv.fn.wapi(
    		{
			    cmd: "GET_PROGRESS",
				T_SNAP: ccv.progress.T_SNAP,
				rnd:  Math.random()    			
    		},
    		
    		function(ret){//success
    			ccv.fn.cbProgress(ret);
    		},
    		
			function() {//error
			    ccv.fn.resetProgress();
				alert("time out");
			}    		
    	);
    },
    
    cbProgress: function(ret) {
        var content = ret.content;
        
    	if (content == "-1000") {
            ccv.fn.resetProgress(true);
    		ccv.domJQ.HISTORY.attr("src", ccv.domJQ.HISTORY.attr("src") +  "?rnd=" + Math.random());        
    	} else {
    		var len = content.length;
    		if (len > ccv.progress.retLength) {
    			ccv.progress.times = 0;
    			ccv.progress.retLength = len;
    			ccv.domJQ.PROGRESS.html(content);
    		} else {
    			if (ccv.progress.times % ccv.progress.TimesBatchCnt == 0 ) {
    			    ccv.domJQ.PROGRESS.html(content + '<span class="queryBatchTimesNo">' + (ccv.progress.times / ccv.progress.TimesBatchCnt + 1) + '</span> ');
    			}
    			
    			ccv.progress.times ++;
    			ccv.domJQ.PROGRESS.html(ccv.domJQ.PROGRESS.html() + "...");    
    		}
    		
    		ccv.domJQ.PROGRESS.attr("scrollTop",  ccv.domJQ.PROGRESS.attr("scrollTop") + ccv.domJQ.PROGRESS.attr("scrollHeight"));       
    	} 
    }, 
    
    resetProgress: function(/*boolean*/ keepProgressInfo) {
        if (!keepProgressInfo) {
            ccv.domJQ.PROGRESS.html("");
        }
        
        if (ccv.progress.interval) {
            clearInterval(ccv.progress.interval);    
        }
        ccv.progress.interval = 0;
        ccv.progress.retLength = 0;
        ccv.progress.times = 0;
    },  
    
    runGenerate: function(pms) {
        ccv.fn.resetProgress();
        
        ccv.domJQ.PROGRESS.text("");
        ccv.domJQ.DLG_PROGRESS.dialog('open');

    	ccv.fn.wapi(
    		pms,
    		
    		function(ret){//success
          	    ccv.progress.T_SNAP = ret.T_SNAP;
                ccv.progress.interval = setInterval(function() {
                    ccv.fn.listenProgress();
                }, 2000);   
    		},
    		
			function() {//error
                ccv.fn.resetProgress();
                alert("Error");  
			}    		
    	);
    }    
};



/**
 * ===========================================================================================
 * ccv ui functions
 * 
 */
ccv.uifn = {
    tip: function(content) {
        Tip(content, CLICKCLOSE, true, STICKY, true, SHADOW, true, ABOVE, false, FADEIN, 500, FADEOUT, 500);
    },
        
    layoutMsgDiv: function() {
        ccv.domJQ.MSG.css({
            "width": ccv.domJQ.HEADER.width() - 2,
            "height": ccv.domJQ.HEADER.height() - 2
        });
    },
    
    layoutCCV: function() {
        var w = jQuery(window).width() - 20;
        ccv.domJQ.HEADER.css("width", w);
        ccv.domJQ.MAIN.css("width", w);
        
        var cfgModulesW = w - ccv.domJQ.USER_ACTIONS.width() - ccv.domJQ.HISTORY.width() -10;
        ccv.domJQ.CFG_MODULES.css("width", cfgModulesW);
        
        ccv.uifn.layoutMsgDiv();
        ccv.ajaxupload.executor.layoutAll();
    },

    
    resetMsgInterval: function() {
        ccv.domJQ.MSG.css("visibility", "hidden");
        clearInterval(ccv.msgInterval);
        ccv.msgInterval = 0;            
    },
    
    showMsg: function(msg, type) {
        if (ccv.msgInterval) {
            ccv.uifn.resetMsgInterval();
        }
        
        ccv.domJQ.MSG.text(msg).css("visibility", "visible");
        ccv.msgInterval = setInterval(function() {
             ccv.uifn.resetMsgInterval();
        }, 3000);
    },


    refreshModules: function(modules) {
        ccv.domJQ.MODULES.hide();
        ccv.domJQ.ALL_ANCHOR.attr("checked", false);
        ccv.domJQ.MODULE_ANCHORS.attr("checked", false).val("");
        ccv.uifn.changeModulesBG(false, ccv.domJQ.MODULES);
        
        var toDynamicModuleItems = function() {
        	var delta =  modules.length - ccv.domJQ.MODULES.length;
        	if (delta <= 0 ) {
        		if (modules.length <= 50 && ccv.domJQ.MODULES.length > 50) {
        			ccv.domJQ.MODULES.slice(50).detach();
        			ccv.domJQ.MODULES = ccv.domJQ.MODULES_CONTAINER.find("div.module");
        		}
        		
        		return;
        	}
        	
        	var addedItems = "";
        	for (var i = 0; i < delta; i++) {
        		addedItems += ccv.ModuleItemHtml + "\n";
        	}
        	
        	ccv.domJQ.MODULES_CONTAINER.append(addedItems);
        	ccv.domJQ.MODULES = ccv.domJQ.MODULES_CONTAINER.find("div.module");
        };
        
        toDynamicModuleItems();
        
        for (var i = 0; i < modules.length; i++) {
            var jqModule = ccv.domJQ.MODULES.eq(i);
            jqModule.find("div.anchor input").val(modules[i].id);
            jqModule.find("div.moduleInfo span.moduleId").html(modules[i].id);
            var jqType = jqModule.find("div.moduleInfo span.moduleType").html("(" + modules[i].type + ")");
            
            var moduleHtmlDetails = "";
            if (modules[i].type == "cvs") {
            	jqModule.removeClass("svn");
            	jqType.removeClass("typeSVN");
            	moduleHtmlDetails = modules[i].module + "<br>" + modules[i].repositoryPath;
            } else {
            	jqModule.addClass("svn");
            	jqType.addClass("typeSVN");
            	moduleHtmlDetails = modules[i].module + "<br><span class='svnRevBase fixwidth'>trunk: </span>" + modules[i].trunkFullPath + "<br><span class='svnRevBase fixwidth'>branch: </span>" + modules[i].branchFullPath + "<br><span class='svnRevBase fixwidth'>tag: </span>" + modules[i].tagFullPath;
            }
            jqModule.find("div.moduleInfo span.moduleDetails").html(moduleHtmlDetails);
            jqModule.show();
        }          
    },
    
    insertEntry2CfgsDom: function(cfgs, defaultCfg) {
        var opts = "";
        for (var i = 0; i < cfgs.length; i++) {
            var flagChecked = (cfgs[i] == defaultCfg) ? " selected" : "";
			opts += "<option" + flagChecked + ">" + cfgs[i] + "</option>";
        }
     
        ccv.domJQ.CFG_SELECT.html(opts).css("width", "150px");
    },
    
    changeModulesBG: function(checkedOn, jqM) {
        if (checkedOn) {
            jqM.addClass("bkChecked");        
        } else {
            jqM.removeClass("bkChecked");
        }
    },
    
    behaviorModuleItmes: function() {
    	jQuery.each(ccv.domJQ.MODULE_ANCHORS, function(index) {
    		if (ccv.domJQ.MODULE_ANCHORS.eq(index).attr('checked')) {
    			ccv.uifn.changeModulesBG(true, ccv.domJQ.MODULES.eq(index));
    		}
    	});
    },
    
    
    htmlSvnRevBaseDoms: function() {
    	var opts = [
    		{k: "branch", v: "Is branch"},
    		{k: "trunk", v: "Is trunk"},
    		{k: "OnTrunk", v: "On trunk"},
    		{k: "OnBranch", v: "On branch"},
    		{k: "tag", v: "Is tag"}
    	];
    	
    	var revOptHtml = "";
    	var dateOptHtml = "<option value='" + opts[2].k + "'>" + opts[2].v + "</option>\n<option value='" + opts[3].k + "'>" + opts[3].v + "</option>\n";
    	for (var i = 0; i < opts.length; i++) {
    		var strChecked = opts[i].k == "branch" ? "checked" : "";
    		revOptHtml += "<option value='" + opts[i].k + "' " + strChecked + ">" + opts[i].v + "</option>\n";
    	}
    	
		ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base, .svnRev2Base").html(revOptHtml);
		ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base, .svnDate2Base").html(dateOptHtml).attr("disabled", true).addClass("gray");   	  	
    },
    
	behaviorDiffDoms: function() {
	    if (ccv.domJQ.RADIO_DIFF_AGAINST.filter(':checked').val() == "dates") {
	        ccv.domJQ.DIFF.find("input.Wdate").attr("disabled", false).removeClass("gray");
	        ccv.domJQ.DIFF.find("input.revision").attr("disabled", true).addClass("gray");
	        ccv.domJQ.DIFF.find("input.branchRevsBasedOn").attr("disabled", true).addClass("gray");
	        ccv.domJQ.DIFF.find("input.branchDatesBasedOn").attr("disabled", false).removeClass("gray");
	        
	        ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base, .svnRev2Base").attr("disabled", true).addClass("gray");
	        ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base, .svnDate2Base").attr("disabled", false).removeClass("gray");
	        
	        ccv.uifn._revBasedSlt2BranchInput(ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base"), ccv.domJQ.DIFF.find("input.branchDatesBasedOn"));
	        
	    } else {
	        ccv.domJQ.DIFF.find("input.Wdate").attr("disabled", true).addClass("gray");
	        ccv.domJQ.DIFF.find("input.revision").attr("disabled", false).removeClass("gray");
	        ccv.domJQ.DIFF.find("input.branchDatesBasedOn").attr("disabled", true).addClass("gray");
	        ccv.domJQ.DIFF.find("input.branchRevsBasedOn").attr("disabled", false).removeClass("gray");
	        
	        ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base, .svnRev2Base").attr("disabled", false).removeClass("gray");
	        ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base, .svnDate2Base").attr("disabled", true).addClass("gray");
	        
	        ccv.uifn._revBasedSlt2BranchInput(ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base"), ccv.domJQ.DIFF.find("input.branchRevsBasedOn"));
 	    } 
	},
	
	_revBasedSlt2BranchInput: function(jqSlt, jqInput) {
		if (jqSlt.val() == "OnBranch") {
			jqInput.attr("disabled", false).removeClass("gray");
		} else {
			jqInput.attr("disabled", true).addClass("gray");
		}
	},
	
	_revBasedSlt2RevsInput: function() {
		if (ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base").val() == "trunk") {
			ccv.domJQ.DIFF.find("input.rev1").attr("disabled", true).addClass("gray");
		} else {
			ccv.domJQ.DIFF.find("input.rev1").attr("disabled", false).removeClass("gray");
		}
		
		if (ccv.domJQ.SVN_REV_BASE.filter(".svnRev2Base").val() == "trunk") {
			ccv.domJQ.DIFF.find("input.rev2").attr("disabled", true).addClass("gray");
		} else {
			ccv.domJQ.DIFF.find("input.rev2").attr("disabled", false).removeClass("gray");
		}			
	},
	
	behaviorSvnDateRevBaseDomsRestriction: function() {
		var jqBranchRevsBasedOn = ccv.domJQ.DIFF.find("input.branchRevsBasedOn");
		var jqBranchDatesBasedOn = ccv.domJQ.DIFF.find("input.branchDatesBasedOn");
		
		var jqRevsDfBase = ccv.domJQ.SVN_REV_BASE.filter(".svnRev1Base, .svnRev2Base").change(function() {
			if (this.value.indexOf("On") == 0) {
				if (jQuery(this).attr("class").indexOf("svnRev1Base") > 0) {
					jqRevsDfBase.filter(".svnRev2Base").val(this.value)
				} else {
					jqRevsDfBase.filter(".svnRev1Base").val(this.value)
				}
			}
			
			ccv.uifn._revBasedSlt2RevsInput();
			ccv.uifn._revBasedSlt2BranchInput(jQuery(this), jqBranchRevsBasedOn);
		});

		var jqDatesDfBase = ccv.domJQ.SVN_REV_BASE.filter(".svnDate1Base, .svnDate2Base").change(function() {
			if (jQuery(this).attr("class").indexOf("svnDate1Base") > 0) {
				jqDatesDfBase.filter(".svnDate2Base").val(this.value)
			} else {
				jqDatesDfBase.filter(".svnDate1Base").val(this.value)
			}			
			ccv.uifn._revBasedSlt2BranchInput(jQuery(this), jqBranchDatesBasedOn);
		});
	}
};



/**
 * ===========================================================================================
 * ccv util functions
 * 
 */
ccv.util = {
	addClassInfo2Body: function() {
		var clz = jQuery.browser.msie ? "ie" : jQuery.browser.mozilla ?  "firefox" : jQuery.browser.chrome ?  "chrome" : jQuery.browser.safari ?  "safari" : ""; 
		if (clz) {
			jQuery(document.body).addClass(clz);
		}
	}
};



/**
 * ===========================================================================================
 * ccv CB functions
 * 
 */

ccv.cb = {
    successGetOverall: function(ret) {
        ccv.uifn.insertEntry2CfgsDom(ret.CFG_FILES, ret.CFG_FILE);
        ccv.uifn.refreshModules(ret.MODULES);
    },
   
    errorGetOverall: function() {
        alert("GetOverall error");
    },
    
    successGetModules: function(ret) {
        ccv.uifn.refreshModules(ret.MODULES);
        jQuery.cookie(ccv.CK_CFG, ccv.domJQ.CFG_SELECT.val());
    },
   
    errorGetModules: function() {
        
    },
    
    successUpload: function(ret) {
  
    },
   
    errorUpload: function() {
        
    }, 
    
    successDelete: function(ret) {
        if (ret.error == 0) {
            var domCfgSelect = ccv.domJQ.CFG_SELECT[0];
            domCfgSelect.remove(domCfgSelect.selectedIndex);
            domCfgSelect.selectedIndex = 0;
            ccv.fn.wapi({cmd: "GET_MODULES", cfg: domCfgSelect.value}, ccv.cb.successGetModules, ccv.cb.errorGetModules);
            ccv.uifn.showMsg("Deleted successfully");
        } else {
            ccv.uifn.showMsg("Delete failed");
        }
        
        ccv.domJQ.DLG_DELETE.dialog("close");
    },
   
    errorDelete: function() {
        
    }      
};

